<?php
/**
 * 微信媒体类
 * User: narnia
 * Date: 2017/5/19
 * Time: 11:24
 */
namespace LancerWechat;

class WechatMedia extends WechatService
{
    public $key = 'media';

    /**
     * 上传素材
     * @param string $image 图片
     * @param string $type 类型
     * @param string $path  本地保存图片路径
     */
    public function upload(string $image, string $type = 'image',string $path = 'data/uploads/wxmedia')
    {
        $url = $this->getUrl([
            '{access_token}' => $this->config['global']['access_token']
        ], [$this->key, 'uploadImg']);
        $path = 'data/uploads/wxmedia';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $fileName = explode('/', $image);
        $fileName = time() . '_' . mt_rand(0000, 9999) . end($fileName);
        $file = $path . '/' . $fileName;
        file_put_contents($file, file_get_contents($image));
        $data = [
            'media' => new \CURLFile(realpath($file)),
            'type' => $type
        ];
        $result = \LancerWechat\WechatFunction::curl($url, $data);
        unlink($file);
        \LancerWechat\WechatLog::write($this->config['log']['path'], $result);
        return $result;
    }

}